package com.hrzyit.whistle.comm.ui.fragment

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.whistle.comm.R
import com.hrzyit.whistle.comm.data.bean.ContactEntity
import com.hrzyit.whistle.comm.injection.component.DaggerContactCenterComponent
import com.hrzyit.whistle.comm.injection.module.ContactCenterModule
import com.hrzyit.whistle.comm.presenter.ContactInfoPresenter
import com.hrzyit.whistle.comm.presenter.view.ContactInfoView
import kotlinx.android.synthetic.main.fragment_user_info.*
import org.jetbrains.anko.support.v4.makeCall
import org.jetbrains.anko.toast

/**
 * 通讯录：个人信息 Fragment
 * @author YangWei
 * @date 2019/4/19
 */
class UserInfoFragment : BaseMvpFragment<ContactInfoPresenter>(), ContactInfoView {

    // 获取当前选择的单位id
    private var userId: Long? = null


    private lateinit var activity: Activity

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as Activity

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_user_info, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        initData()

    }

    private fun initView(){
        // 注册拨打电话操作
        mCallPhoneIv.onClick {
            mMobileTv?.let {
                // 调用拨打电话组件
                Log.e("startCallPhone", it.text.toString())
//                startCallPhone(it.text.toString())
                val phone = "13141456727"
                makeCall(phone)
            }
        }
    }

    /**
     * 加载数据
     */
    private fun initData() {
        // 获取参数：单位id
        userId = activity.intent.getLongExtra("userId", 0L)
        mPresenter.getContactUserDetail(userId!!)
    }


    /**
     * Dagger2 注入
     */
    override fun injectComponent() {

        DaggerContactCenterComponent.builder()
            .activityComponent(mActivityComponent)
            .contactCenterModule(ContactCenterModule())
            .build()
            .inject(this)
        mPresenter.mView = this
    }

    override fun onGetContactUserDetailSuccess(result: ContactEntity) {

        mMobileTv.text = result.mobile
        mUserNameTv.text = result.name
        // 加载头像
//        mUserIconIv.background = result.avatar!!
        mDeptNameTv.text = result.fullName
        mDeptAddressTv.text = result.orgAddress
    }

    // 电话号码
    private lateinit var phoneNumber: String

    /**
     * 拨打电话
     * @param   phoneNumber 电话号码
     */
    private fun startCallPhone(phoneNumber: String) {
        this.phoneNumber = phoneNumber


        val checkCallPhonePermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE)
        when (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            true -> {
                // Android SDK >= 23
                if (checkCallPhonePermission == PackageManager.PERMISSION_GRANTED) {
                    // 已授权直接拨打电话
                    callPhone(phoneNumber)
                } else {
                    // 直接请求授权，动态授权后执行回调：onRequestPermissionsResult
                    ActivityCompat.requestPermissions(
                        activity, arrayOf(Manifest.permission.CALL_PHONE),
                        REQUEST_CALL_PERMISSION
                    )
                    return
                }
            }
            false -> {
                if (checkCallPhonePermission == PackageManager.PERMISSION_GRANTED) {
                    // 已授权直接拨打电话
                    callPhone(phoneNumber)
                } else {
                    // 未授权，申请授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale(
                            this as Activity,
                            Manifest.permission.CALL_PHONE
                        )
                    ) {

                        activity.toast("拨打电话需要授权，请授权")

                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", packageName, null)
                        intent.data = uri
                        startActivity(intent)
                    } else {
                        // 直接请求授权，动态授权后执行回调：onRequestPermissionsResult
                        ActivityCompat.requestPermissions(
                            this, arrayOf(Manifest.permission.CALL_PHONE),
                            REQUEST_CALL_PERMISSION
                        )
                    }
                }
            }
        }

    }

    /**
     * 拨打电话界面
     */
    private fun callPhone(phoneNumber: String) {
        val uri = Uri.parse("tel:$phoneNumber")
        // 打开拨号界面，填充输入手机号码，让用户自主的选择:ACTION_DIAL
        // 直接拨打电话
        val intent = Intent(Intent.ACTION_CALL, uri)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        try {
            startActivity(intent)
        } catch (se: SecurityException) {
            Log.e("Question for permission", "拨打电话未授权")
        }
    }

    /**
     * 判断是否有某项权限
     * @param   permission    权限
     * @param   requestCode     请求码
     * @return  boolean
     */
//    fun checkReadPermission(permission: String, requestCode: Int): Boolean {
//        var flag = false
//        when (PackageManager.PERMISSION_GRANTED) {
//            ContextCompat.checkSelfPermission(this, permission) -> {
//                flag = true
//            }
//            else -> {
//                // 申请权限
//                ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
//            }
//        }
//        return flag
//    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            REQUEST_CALL_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    callPhone(this.phoneNumber)
                } else {
                    activity.toast("授权失败")
                }
            }
        }
    }


    companion object {
        const val REQUEST_CALL_PERMISSION = 10111
    }
}